import Vue from 'vue'

// 千分位
Vue.directive('thousands', {
  bind (el, binding, vnode) {
    const key = Object.keys(binding.modifiers)[0]
    if (!binding.value[key]) {
      binding.value[key] = "0.00"
    }
    // 处理千分位展示
    const generatingThousandthPer = (num) => {
      let num1 = num.split(".")[0], num2 = num.split(".")[1] ? num.split(".")[1].slice(0, 2) : "00";
      let c = num1.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
      return c + "." + num2
      // return num.toString().indexOf(".") !== -1 ? c + "." + num2 : c;
    }
    // 赋值
    const assignment = (event, value, value2) => {
      binding.value[key] = value;
      vnode.context.$nextTick(() => event.target.value = generatingThousandthPer(value2 || value))
    }
    // 处理最后一位非法字符
    const handlerIllegalStr = (str) => {
      while (!(/^[0-9]+.?[0-9]*/.test(str.charAt(str.length - 1)))) {
        str = str.substr(0, str.length - 1)
      }
      return str
    }

    // el.addEventListener("input", (event) => {
    // let inp = event.target.value = event.target.value.replace(/,/g, "")
    // assignment(event, inp)
    // })

    // element
    // eslint-disable-next-line no-undef
    // const input = el.querySelector(".el-input__inner")
    const input = el.querySelector("input")

    if (input) {

      input.setAttribute("data-thousands", binding.value[key]);
      vnode.context.$nextTick(() => input.value = generatingThousandthPer(binding.value[key] + ""))

      input.addEventListener("blur", (event) => {
        const val = event.target.value;
        // 是否是数字
        if (!val || isNaN(val)) {
          /**
           * 如果不是数字 重置为原数据
           */
          const value = input.getAttribute("data-thousands");
          binding.value[key] = value.replace(/,/g, "")
          vnode.context.$nextTick(() => event.target.value = generatingThousandthPer(value))
          return false;
        }
        input.setAttribute("data-thousands", val);
        assignment(event, handlerIllegalStr(val.replace(/,/g, "")))
      })

      input.addEventListener("focus", (event) => {
        let value = input.getAttribute("data-thousands");
        let inp = event.target.value = value.replace(/,/g, "")
      })
    }
  }
});